package cn.project.engineering.http

import cn.project.engineering.BuildConfig
import cn.project.engineering.utils.WonderSp
import com.google.gson.Gson
import com.hjq.gson.factory.GsonFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import java.util.concurrent.TimeUnit

/**
 *
 * @author  lifuhai@linkcircle.cn
 * @date 2021/2/18 15:00
 */


object HttpClient {
//    private const val BASE_URL = "http://www.kingshiyi.com/"
    private  var BASE_URL = "http://www.baidu.com/"
    @JvmStatic fun  setUrl(url :String){
        BASE_URL=url
    }
    @JvmStatic fun  getUrl():String{
        return BASE_URL
    }


    //局域网地址
//    private const val BASE_URL = "http://192.168.10.32:8097/"
    private const val HTTP_CONNECT_TIMEOUT = 15L//请求连接超时
    private const val HTTP_WRITE_TIMEOUT = 5L//请求写超时
    private const val HTTP_READ_TIMEOUT = 5L//请求读超时

    private var retrofit: Retrofit

    init {
        retrofit = Retrofit.Builder().baseUrl(BASE_URL)
                .client(createOkHttp())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(CustomGsonConverterFactory.create(createGson()))
                .build()
    }

     @JvmStatic fun httpService(): ApiService {
        return retrofit.create(ApiService::class.java)
    }

    @JvmStatic fun changeUrl(Url:String) {
        retrofit= retrofit.newBuilder().baseUrl(Url).client(createOkHttp())
              .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(CustomGsonConverterFactory.create(createGson())).build();
    }

    private fun createGson(): Gson {
        return GsonFactory.createGsonBuilder()
                // 统一日期请求格式
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .setLenient()
                .create()
    }

    private fun createOkHttp(): OkHttpClient {
        val builder = OkHttpClient.Builder()
                .connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(HTTP_WRITE_TIMEOUT, TimeUnit.MINUTES)
                .readTimeout(HTTP_READ_TIMEOUT, TimeUnit.MINUTES)

        if (BuildConfig.DEBUG) {
            // debug模式下输出日志
            builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        }

        return builder.build()
    }
}